import 'package:dio/dio.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

class HttpClient {
  final Dio _dio = Dio();

  HttpClient() {
    // 基础配置
    _dio.options.baseUrl = 'https://api.your-ecommerce.com/v1'; // 替换为你的后端API地址
    _dio.options.connectTimeout = const Duration(seconds: 15);
    _dio.options.receiveTimeout = const Duration(seconds: 15);
    _dio.options.headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };

    // 调试日志拦截器（仅调试模式启用）
    _dio.interceptors.add(
      PrettyDioLogger(
        requestHeader: true,
        requestBody: true,
        responseBody: true,
        responseHeader: false,
        error: true,
        compact: true,
      ),
    );

    // 认证拦截器
    _dio.interceptors.add(_authInterceptor());
  }

  Interceptor _authInterceptor() {
    return InterceptorsWrapper(
      onRequest: (options, handler) {
        // 从本地存储获取token（如shared_preferences）
        // final token = await storage.read('auth_token');
        // if (token != null) {
        //   options.headers['Authorization'] = 'Bearer $token';
        // }
        return handler.next(options);
      },
      onError: (error, handler) async {
        // 处理401未授权错误
        if (error.response?.statusCode == 401) {
          // 1. 清除本地token
          // 2. 跳转到登录页
          // 3. 可以选择刷新token然后重试请求
        }
        return handler.next(error);
      },
    );
  }

  // 公开的请求方法
  Future<Response> get(String path, {Map<String, dynamic>? params}) async {
    return _dio.get(path, queryParameters: params);
  }

  Future<Response> post(String path, {dynamic data}) async {
    return _dio.post(path, data: data);
  }

  Future<Response> put(String path, {dynamic data}) async {
    return _dio.put(path, data: data);
  }

  Future<Response> delete(String path) async {
    return _dio.delete(path);
  }

  // 文件上传
  Future<Response> upload(
    String path, {
    required String filePath,
    ProgressCallback? onProgress,
  }) async {
    FormData formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(filePath),
    });
    return _dio.post(path, data: formData, onSendProgress: onProgress);
  }
}
